import axios from 'axios';
import {showMessage} from "./status";   // 引入状态码文件
import {ElMessage, ElMessageBox, ElLoading} from 'element-plus'  // 引入el 提示框，这个项目里用什么组件库这里引什么
import {useUserStore} from "@/store/user";
import {useCookies} from "vue3-cookies";
import router from "@/router";

const {cookies} = useCookies();

// 设置接口超时时间
axios.defaults.timeout = 30000;
// 请求地址，这里是动态赋值的的环境变量，下一篇会细讲，这里跳过
// @ts-ignore
axios.defaults.baseURL = import.meta.env.VITE_BASE_URL;

// axios.defaults.headers.common['token'] = cookies.get('lstoken') || ''; //尝试解决第一次token拿不到的问题
//http request 拦截器
axios.interceptors.request.use(
    config => {
        // const token = cookies.get('lstoken') || '';
        // console.log(token,'config of token')
        // 配置请求头
        // config.headers = {
        //     // 'Content-Type': 'application/x-www-form-urlencoded',   // 传参方式表单
        //     'Content-Type': 'application/json;charset=UTF-8',        // 传参方式json
        //     // 'token': 'aa53b31ad819523405c638575fcb9f75'           // 这里自定义配置，这里传的是token
        //     token: token
        // };
        // config.headers.common['token'] = token;
        console.log(config, 'config')
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

let messageBoxFlag = 0 // 默认 MessageBox 未打开

//http response 拦截器
axios.interceptors.response.use(
    response => {
        console.log(response, 'response')
        if (response?.data?.status === 401 && messageBoxFlag === 0) {
            let errTxt = ",是否返回登录？";
            messageBoxFlag = 1 // 修改标记，打开 MessageBox
            ElMessageBox.confirm(response?.data?.msg + errTxt, '提示', {
                type: 'warning',
                showClose: false,
                showCancelButton: false,
                closeOnClickModal: false,
                closeOnPressEscape: false,
            }).then(() => {
                messageBoxFlag = 0  // 修改标记
                const user = useUserStore();
                // const loginurl = cookies.get('loginurl') || user.userInfo.loginurl;
                user.setUserInfo({});
                cookies.remove("pktoken");
                // window.location.href = loginurl
                router.push('/login')
            }).catch(() => {
                messageBoxFlag = 0  // 修改标记
            });
        }
        return response;
    },
    error => {
        const {response} = error;
        if (response) {
            // 请求已发出，但是不在2xx的范围
            showMessage(response.status);           // 传入响应码，匹配响应码对应信息
            return Promise.reject(response.data);
        } else {
            ElMessage.warning('网络连接异常,请稍后再试!');
        }
    }
);

let timerId, loading;

const removeLoading = () => {
    if (timerId) clearTimeout(timerId);
    loading?.close && loading?.close()
};

// 封装 GET POST 请求并导出
export function request(url = '', params = {}, type = 'POST', needToken = true) {
    // axios.withCredentials = true;
    if (needToken) {
        const token = cookies.get('pktoken');
        axios.defaults.headers.common['Authorization'] = token;
    }
    if (timerId) clearTimeout(timerId)
    timerId = setTimeout(() => {
        loading = ElLoading.service({
            lock: true,
            text: 'Loading',
            background: 'rgba(0, 0, 0, 0.7)',
        })
    }, 300)
//设置 url params type 的默认值
    return new Promise((resolve, reject) => {
        let promise: any;
        if (type.toUpperCase() === 'GET') {
            promise = axios({
                url,
                params
            })
        } else if (type.toUpperCase() === 'POST') {
            promise = axios({
                method: 'POST',
                url,
                data: params
            })
        }
        //处理返回
        promise.then((res: any) => {
            removeLoading();
            resolve(res)
        }).catch((err: any) => {
            removeLoading();
            reject(err)
        })
    })
}
